package com.zretc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller

public class FileDownloadController {

    @RequestMapping("/fileDownload/{fileName:.+}")
    public void getFile(@PathVariable(value = "fileName") String fileName, HttpServletResponse response) throws ServletException, IOException {
        // 存储头像的文件目录
        String root = "C:/image/";
        // 关联文件
        File file = new File(root + fileName);
        // 通过字节读取流 读文件
        FileInputStream fis = new FileInputStream(file);

        // 字节数组输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;

        // 边读边写
        while ( (n = fis.read(b)) != -1) { // 有数据可读
            // 写
            bos.write(b,0,n);
        }
        bos.close();
        fis.close();
        // 通过Servlet输出流将文件以字节数组的形式输出到网页上
        ServletOutputStream sos = response.getOutputStream();
        sos.write(bos.toByteArray());
        sos.flush();
        sos.close();
    }
}
